<template>
  <div class="app-container">
    <div>
      <!-- <el-row class="admin-top-g">
        <GButton
          :is-add-show="false"
          :is-del-show="false"
          :is-edit-show="false"
          :is-settings-show="false"
        />
      </el-row> -->

      <el-row>
        <el-date-picker
          v-model="qjValue"
          style="width: 195px;"
          type="month"

          placeholder="选择年度"
          @change="selectPeriod"/>
        <el-select v-model="fcompany" clearable filterable placeholder="请选择公司" @change="searchUser">
          <el-option
            v-for="item in gsList"
            :key="item.finterid"
            :label="item.fname"
            :value="item.fname"/>
        </el-select>

        <el-select v-model="fdeptname" clearable filterable placeholder="请选择部门" @change="searchUser">
          <el-option
            v-for="item in bmList"
            :key="item.finterid"
            :label="item.fname"
            :value="item.fname"/>
        </el-select>

        <el-input v-model="fname" clearable style="width: 160px;" placeholder="请输入员工姓名" @keyup.native.enter="calculate"/>
        <el-button v-if="isBtn" type="danger" icon="el-icon-check" @click="calculate">计算</el-button>
        <el-button v-else type="success" icon="el-icon-news" @click="saveWage">保存</el-button>
        <el-button type="success" icon="el-icon-back" @click="back">返回工资汇总页面</el-button>
      </el-row>
    </div>
    <br>
    <el-table
      v-loading="listLoading"
      :key="key"
      :data="tableData"
      max-height="750"
      element-loading-text="正在加载"
      border
      fit
      highlight-current-row
      @selection-change="handleSelectionChange">
      <el-table-column
        type="selection"
        width="55"/>
      <!-- <el-table-column v-for="item in formThead" :width="item.frepwid" :key="item.frepindex" :label="item.frepcap" align="center"> -->
      <el-table-column v-for="item in formThead" :key="item.fid" :label="item.frepcap" :width="item.frepwid" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          <template v-if="item.frephide <=0">
            <template v-if="item.frepfld === 'fstatus'">
              <el-tag v-if="Number(scope.row[item.frepfld]) === 1" type="success">已审</el-tag>
              <el-tag v-else type="danger">未审</el-tag>
            </template>
            <template v-else-if="item.frepfld === 'ffustatus'">
              <el-tag v-if="Number(scope.row[item.frepfld]) === 1" type="success">已复审</el-tag>
              <el-tag v-else type="danger">未复审</el-tag>
            </template>
            <template v-else-if="item.frepfld === 'fhiredate'">
              {{ scope.row[item.frepfld] ? scope.row[item.frepfld].split('-').join(''): '' }}
            </template>
            <template v-else>
              {{ scope.row[item.frepfld] }}
            </template>
          </template>
        </template>
      </el-table-column>

    </el-table>

    <!-- SQL弹窗 -->
    <el-dialog v-el-drag-dialog :visible.sync="dialogSQLModal" :append-to-body="true" title="执行结果">
      <el-form v-loading="loadingFormSQL" ref="formSQL" :rules="rulesSQL" :model="formSQL" label-width="120px">
        <el-form-item label="SQL语句" prop="gzsql">
          <el-input v-model="formSQL.gzsql" :autosize="{ minRows: 14 }" type="textarea"/>
        </el-form-item>
        <el-form-item>
          <el-button :loading="loadingFormSQL" type="primary" @click="confirmSQL" >确认</el-button>
          <el-button @click="dialogSQLModal=false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

  </div>
</template>
<script>
let FRepKey = ''
const defaultFormThead = []
const date = new Date().getDate()
const t = new Date(new Date().getTime() - date * 24 * 60 * 60 * 1000)
// const t = new Date(new Date().getTime() - 30 * 24 * 60 * 60 * 1000)
const defaultOptions = [
  {
    value: 1,
    label: '显示SQL语句'
  }
]
import { common } from '../../mixins/common'
import { company } from '../../mixins/company'
import { bumen } from '../../mixins/bumen'
import { configColumn, jisuan, scgzSave } from '../../api/salary'
import HeadTable from './headTable/index.vue'
import { apiSql, apiFileSave } from '../../api/account'
import { periodList, getYearMonth } from '../../utils/index'
export default {
  name: 'Index',
  components: {
    HeadTable
  },
  mixins: [common, bumen, company],
  data() {
    return {
      // 弹窗下拉列表
      periodList: [],
      fcompany: '',

      value: '',
      options: [],
      FRepKey: '',
      fname: '',
      qjValue: getYearMonth(t),
      // keyword: '',
      isBtn: true,
      // 表头、表格设置
      tableData: [],
      defaultFormThead: [],
      formThead: defaultFormThead,
      dialogThead: [],
      curData: {},
      rows: [], // 选中的数据

      listLoading: false,
      list: [],

      addUserModal: false,
      loadingForm: false,
      isEditor: false,
      // 参数配置
      configLoading: false,
      key: 0,

      // SQL弹窗
      dialogSQLModal: false,
      loadingFormSQL: false,
      formSQL: {
        gzsql: ''
      },
      rulesSQL: {

      }
    }
  },
  mounted() {
    FRepKey = this.$route.meta.FRepKey
    this.options = defaultOptions
    this.periodList = periodList
    this.getHeadData()
  },
  methods: {
    calculate() {
      this.getBodyData()
    },
    async saveWage() {
      if (this.rows.length <= 0) {
        this.$message({
          message: '请选中表格记录，再保存',
          type: 'warning'
        })
        return
      }
      try {
        this.listLoading = true
        const res = await scgzSave({
          db: this.globalDb.db,
          opername: decodeURIComponent(this.globalDb.fname),
          rows: this.rows
        })
        this.listLoading = false
        console.log(res, ' res')
        if (res.Error === 0) {
          this.$router.push({
            path: '/salary/paySheet',
            query: {
              qjValue: this.qjValue
            }
          })
        }
      } catch (error) {
        this.listLoading = false
        console.log(error)
      }
    },
    back() {
      this.$router.push('/salary/paySheet')
    },
    selectSettings(val) {
      // console.log(val, ' val SQL')
      this.dialogSQL()
    },
    handleSelectionChange(val) {
      console.log(val, ' val ')
      this.rows = val
    },
    // 表头数据
    async getHeadData() {
      try {
        this.listLoading = true
        const res = await configColumn({
          db: this.globalDb.db,
          opername: decodeURIComponent(this.globalDb.fname),
          FRepKey: 12011
        })
        this.listLoading = false

        const brr = res.Data
        brr.map((it, index) => {
          if (it.frepfld === 'fstatus') {
            brr.splice(index, 1)
          }
        })

        // this.formThead = res.Data
        this.formThead = brr
        // 去除内码
        const arr = res.Data.slice()
        arr.map((item, index) => {
          if (item.frepfld === 'FItemID') {
            arr.splice(index, 1)
          }
        })

        this.dialogThead = arr.filter(item => item.funcontrol !== 1)
        // console.log(res.Data, ' res.Data')
      } catch (error) {
        this.listLoading = false
        console.log(error)
      }
    },
    // 表体数据  计算数据
    async getBodyData() {
      try {
        this.listLoading = true
        const res = await jisuan({
          db: this.globalDb.db,
          opername: decodeURIComponent(this.globalDb.fname),
          fname: this.fname,
          qjValue: this.qjValue,
          fcompany: this.fcompany,
          fdeptname: this.fdeptname,
          rows: []
        })
        if (res.Error === 0) {
          this.isBtn = false
          this.$message({
            message: res.Message,
            type: 'success'
          })
        } else {
          this.$message({
            message: res.Message,
            type: 'warning'
          })
        }
        this.formThead.map(item => {
          res.result.map(it => {
            if (item.freptype === 131) {
              it[item.frepfld] = Number(it[item.frepfld]).toFixed(item.fdecplaces)
            }
          })
        })
        this.tableData = res.result.slice()
        this.listLoading = false
        console.log(res, this.tableData, ' res')
      } catch (error) {
        this.listLoading = false
        console.log(error)
      }
    },
    selectPeriod(val) {
      this.qjValue = getYearMonth(val)
      console.log(this.qjValue, '  this.qjValue')
      this.searchUser()
    },
    searchUser() {
      this.getBodyData()
    },

    // SQL修改/更新
    async dialogSQL() {
      this.dialogSQLModal = true
      try {
        const res = await apiSql({
          db: this.globalDb.db,
          opername: decodeURIComponent(this.globalDb.fname),
          FRepKey
        })
        if (res.Error === 0) {
          this.formSQL.gzsql = res.Data
          this.formSQL.FRepKey = FRepKey
        }
        setTimeout(() => {
          this.$refs['formSQL'].clearValidate()
        })
      } catch (error) {
        console.log(error)
      }
    },
    // SQL保存
    confirmSQL() {
      this.$refs['formSQL'].validate(async(valid) => {
        if (valid) {
          try {
            this.formSQL.db = this.globalDb.db
            this.formSQL.opername = decodeURIComponent(this.globalDb.fname)
            const res = await apiFileSave(this.formSQL)
            if (res.Error === 0) {
              this.dialogSQLModal = false
              this.$message({
                message: res.Message,
                type: 'success'
              })
            } else {
              this.$message({
                message: res.Message,
                type: 'error'
              })
            }
          } catch (error) {
            console.log(error)
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }

  }
}
</script>
<style lang="scss" scoped>
.config-dialog ::v-deep .el-dialog {
  width: 90%;
}
  .el-row div, button {
    margin-top: 10px;
  }
</style>

